﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;

namespace Paltop_v0._1.UI
{//fileID address fileExtention
    public partial class FileManager : System.Web.UI.Page
    {

        private Dictionary<string, string> sampleData = new Dictionary<string, string>();//ba in farz ke key, FileID va value, fileExtention ast.
        public string fileMangerContent = "";
        public string addersBar = "";
        public int currentFolderId = 0;
        public string TreeViewInfo = "";
        public bool backEnable = false;
        public bool forwardEnable = false;
        private Stack<int> BackStack;
        private Stack<int> ForwardStack;
        public int size = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            
            
            Paltop_.Controllers.FileManagerController fmc = new Paltop_.Controllers.FileManagerController();
             //Session["ACCOUNTID"] =10;
            int userId = int.Parse(Session["ACCOUNTID"].ToString());
            
            XElement filelist = null;
            Paltop_.Controllers.SortType sort = (HiddenSort.Value == "title" ? Paltop_.Controllers.SortType.ByTitle : Paltop_.Controllers.SortType.BySize);

            if (Session["BACKSTACK"] == null)
            {
                BackStack = new Stack<int>();
                Session["BACKSTACK"] = BackStack;
                ForwardStack = new Stack<int>();
                Session["FORWARDSTACK"] = ForwardStack;
            }
            else
            {
                BackStack = (Stack<int>)Session["BACKSTACK"];
                ForwardStack = (Stack<int>)Session["FORWARDSTACK"];
            }
            
            switch (HiddenAction.Value)
            {

                case "":
                    {
                        filelist = GoToRoot(fmc, userId, sort);
                        if (Session["ArgumentHistory"] != null)
                            BackStack.Push((int)Session["ArgumentHistory"]);
                        break;

                    }
                case "OPENFOLDER_TREE":
                    {
                        currentFolderId = int.Parse(HiddenArgument.Value); 
                        filelist = OpenTreeFolder(fmc, userId, sort);
                        if (Session["ArgumentHistory"] != null)
                            BackStack.Push((int)Session["ArgumentHistory"]);
                        break;
                    }
                case "REFRESH":
                    {
                        filelist = Refresh(fmc, userId, sort);
                       
                        break;
                    }
                case "OPENFOLDER":
                    {
                        filelist = OpenFolder(fmc, userId, sort);
                        if (Session["ArgumentHistory"] != null)
                            BackStack.Push((int)Session["ArgumentHistory"]);
                        break;
                    }
                case "GOTOPARENT":
                    {
                        filelist = GoToParent(fmc, userId, sort);
                        if (Session["ArgumentHistory"] != null)
                            BackStack.Push((int)Session["ArgumentHistory"]);
                        break;
                    }
                case "BACK":
                    {
                        //BackStack.Pop();
                        currentFolderId = BackStack.Pop();
                        if (currentFolderId == 0)
                        {
                            filelist = GoToRoot(fmc, userId, sort);
                        }
                        else
                        {
                            filelist = OpenTreeFolder(fmc, userId, sort);
                        }
                        ForwardStack.Push((int)Session["ArgumentHistory"]);
                        //ForwardStack.Push(BackStack.Pop());
                        break;
                    }
                case "FORWARD":
                    {
                         
                        currentFolderId = ForwardStack.Pop();
                        if (currentFolderId == 0)
                        {
                            filelist = GoToRoot(fmc, userId, sort);
                        }
                        else
                            filelist = OpenTreeFolder(fmc, userId, sort);
                       // BackStack.Push(ForwardStack.Peek());
                        BackStack.Push((int)Session["ArgumentHistory"]);
                        break;
                    }
            }
            if (BackStack.Count >0)
                backEnable = true;
            if (ForwardStack.Count > 0)
                forwardEnable = true;
            foreach (var item in filelist.Elements("FileAndFolderInfo"))
            {
                string icon = item.Element("ExtentionTitle").Value;
                if (!string.IsNullOrEmpty(item.Element("Description").Value))
                    if (item.Element("Description").Value== "NOT SUPPORTED")
                        icon = "unknown";
                fileMangerContent += "<li class=\"" + (bool.Parse(item.Element("FileFlag").Value) ? "File" : "Folder") + "\"><img style=\"width:16px;height:16px;\" src=\"../TemplateImages/FileExtentions/" +icon + ".png\" /><a id=\"f_" + item.Element("FileInfoID").Value + "\" href=\"#\" onclick=\"" + item.Element("JSFunction").Value + "\">" + item.Element("Title").Value + "</a> </li>";
                size += int.Parse(item.Element("Size").Value);
            }
            size = size / 1024;
            fillAddressBar();
            addersBar = "<span class=\"AdressbarItem\"><img src=\"../TemplateImages/FileExtentions/root.png\" /><a id=\"f_0\" href=\"#\" onclick=\"GotoRootFolder()\">Root</a></span>" + addersBar;
            Stack<int> treeStack = new Stack<int>();
            treeStack.Push(currentFolderId);
            fmc.findePath(treeStack);
            TreeViewInfo = fmc.treeView(userId, treeStack);
            Session["ArgumentHistory"] = currentFolderId;
        }

        private XElement GoToParent(Paltop_.Controllers.FileManagerController fmc, int userId, Paltop_.Controllers.SortType sort)
        {
            int parentId = int.Parse(HiddenArgument.Value);
            Stack<XElement> st = ((Stack<XElement>)Session["ADDRESSBARSTAK"]);
            while (st.Count != 0 && int.Parse(st.Peek().Element("FileInfoID").Value) != parentId)
                st.Pop();
            currentFolderId = parentId;

            XElement filelist = fmc.GetFileAndFolderList(userId, parentId, Paltop_.Controllers.Sort.Ascending, sort);
            
            return filelist;
        }

        private XElement OpenFolder(Paltop_.Controllers.FileManagerController fmc, int userId, Paltop_.Controllers.SortType sort)
        {
            int parentId = int.Parse(HiddenArgument.Value);
            XElement parnent = fmc.GetFileOrFolderInfo(userId, parentId);
            ((Stack<XElement>)Session["ADDRESSBARSTAK"]).Push(parnent);

            XElement filelist = fmc.GetFileAndFolderList(userId, parentId, Paltop_.Controllers.Sort.Ascending, sort);
            currentFolderId = parentId;
             
            return filelist;
        }

        private XElement Refresh(Paltop_.Controllers.FileManagerController fmc, int userId, Paltop_.Controllers.SortType sort)
        {
            currentFolderId = int.Parse(HiddenArgument.Value);
            XElement filelist = fmc.GetFileAndFolderList(userId, currentFolderId, Paltop_.Controllers.Sort.Ascending, sort);
             
            return filelist;
        }

        private XElement OpenTreeFolder(Paltop_.Controllers.FileManagerController fmc, int userId, Paltop_.Controllers.SortType sort)
        {
            Stack<XElement> temp = new Stack<XElement>();
            int parentId = currentFolderId;
            XElement filelist = fmc.GetFileAndFolderList(userId, parentId, Paltop_.Controllers.Sort.Ascending, sort);
           
            temp.Push(fmc.GetFileOrFolderInfo(userId, currentFolderId));
            fmc.fillAddressStack(temp);
            Stack<XElement> addresBarStack = new Stack<XElement>();
            while (temp.Count != 0)
            {
                addresBarStack.Push(temp.Pop());
            }
            Session["ADDRESSBARSTAK"] = addresBarStack;
           
            return filelist;
        }

        private XElement GoToRoot(Paltop_.Controllers.FileManagerController fmc, int userId, Paltop_.Controllers.SortType sort)
        {
            XElement filelist = fmc.GetFileAndFolderList(userId, true, Paltop_.Controllers.Sort.Ascending, sort);
            Stack<XElement> addresBarStack = new Stack<XElement>();
             
            Session["ADDRESSBARSTAK"] = addresBarStack;
            return filelist;
        }
        private void fillAddressBar()
        {
            Stack<XElement> st = (Stack<XElement>)Session["ADDRESSBARSTAK"];
            foreach (var parnent in st)
            {
                addersBar = "<span class=\"AdressbarItem\"><img src=\"../TemplateImages/FileExtentions/" + parnent.Element("ExtentionTitle").Value + ".png\" /><a id=\"f_" + parnent.Element("FileInfoID").Value + "\" href=\"#\" onclick=\"GotoParentFolder(" + parnent.Element("FileInfoID").Value + ")\">" + parnent.Element("Title").Value + "</a></span>" + addersBar;
            }

        }
    }
}
